package com.jiuzhi.app.common.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 * 功能:调用发送http请求 Author:Huang fengge Date:2015年12月29日
 */
public final class HttpUtil {

	private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
	private static final String CONTENT_ENCODING_UTF8 = "UTF-8";
	private static final String CONTENT_TYPE_JSON = "application/json";
	private static final String CONTENT_TYPE_JSON_TWO = "application/x-www-form-urlencoded";

	public static HttpResult httpGet(String url) throws ClientProtocolException, IOException {
		HttpClient httpClient = HttpClients.createDefault();
		HttpGet get = new HttpGet(url);
		HttpResponse result = httpClient.execute(get);
		return new HttpResult(result.getStatusLine().getStatusCode(),
				EntityUtils.toString(result.getEntity(), CONTENT_ENCODING_UTF8));

	}

	/**
	 * http方式POST
	 *
	 * @param url
	 * @param json
	 * @return
	 * @throws IOException
	 */
	public static String httpJsonPost(String url, String json) throws IOException {
		return jsonPost(HttpClients.createDefault(), new HttpPost(url), json);
	}


	public static String httpJsonPostWxEpa(String url, Map<String, Object> map) throws IOException {
		HttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		StringBuilder sb = new StringBuilder();
		if (map != null && map.size() > 0) {
			for (String key : map.keySet()) {
				if (sb.length() > 0) {
					sb.append("&");
				}
				sb.append(key + "=" + String.valueOf(map.get(key)));
			}

			StringEntity entity = new StringEntity(sb.toString(), CONTENT_ENCODING_UTF8);
			entity.setContentEncoding(CONTENT_ENCODING_UTF8);
			entity.setContentType(CONTENT_TYPE_JSON_TWO);
			httpPost.setEntity(entity);
		}
		HttpResponse result = httpClient.execute(httpPost);
		log.info(sb.toString() + ", resultStatusCode:" + result.getStatusLine().getStatusCode());
		return EntityUtils.toString(result.getEntity(), CONTENT_ENCODING_UTF8);
	}

	public static String jsonPost(HttpClient httpClient, HttpPost httpPost, String json) throws IOException {
		if (null != json) {
			StringEntity entity = new StringEntity(json, CONTENT_ENCODING_UTF8);
			entity.setContentEncoding(CONTENT_ENCODING_UTF8);
			entity.setContentType(CONTENT_TYPE_JSON);
			httpPost.setEntity(entity);
		}
		HttpResponse result = httpClient.execute(httpPost);
		log.info(json + ", resultStatusCode:" + result.getStatusLine().getStatusCode());
		return EntityUtils.toString(result.getEntity(), CONTENT_ENCODING_UTF8);
	}

	public static int jsonPostStatus(HttpClient httpClient, HttpPost httpPost, String json) throws IOException {
		if (null != json) {
			StringEntity entity = new StringEntity(json, CONTENT_ENCODING_UTF8);
			entity.setContentEncoding(CONTENT_ENCODING_UTF8);
			entity.setContentType(CONTENT_TYPE_JSON);
			httpPost.setEntity(entity);
		}
		HttpResponse result = httpClient.execute(httpPost);
		// System.out.println("返回状态码:" +
		// result.getStatusLine().getStatusCode());
		// EntityUtils.toString(result.getEntity(), CONTENT_ENCODING_UTF8);
		return result.getStatusLine().getStatusCode();
	}

	/**
	 * postForm请求
	 *
	 * @param url
	 * @param params
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static HttpResult postForm(String url, Map<String, Object> params) throws ParseException, IOException {
		HttpClient httpClient = HttpClients.createDefault();
		HttpPost httpost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();

		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			if (null != params.get(key)) {
				nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
			}
		}
		httpost.setEntity(new UrlEncodedFormEntity(nvps, CONTENT_ENCODING_UTF8));
		HttpResponse result = httpClient.execute(httpost);
		return new HttpResult(result.getStatusLine().getStatusCode(),
				EntityUtils.toString(result.getEntity(), CONTENT_ENCODING_UTF8));
	}




	/**
	 * post请求
	 *
	 * @param url
	 *            功能和操作
	 * @param body
	 *            要post的数据
	 * @return
	 * @throws IOException
	 */
	public static String post(String url, String body) {
		System.out.println("url:" + System.lineSeparator() + url);
		System.out.println("body:" + System.lineSeparator() + body);

		String result = "";
		try {
			OutputStreamWriter out = null;
			BufferedReader in = null;
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();

			// 设置连接参数
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(20000);

			// 提交数据
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			out.write(body);
			out.flush();

			// 读取返回数据
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line = "";
			boolean firstLine = true; // 读第一行不加换行符
			while ((line = in.readLine()) != null) {
				if (firstLine) {
					firstLine = false;
				} else {
					result += System.lineSeparator();
				}
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 回调测试工具方法
	 *
	 * @param url
	 * @param reqStr
	 * @return
	 */
	public static String postHuiDiao(String url, String body) {
		String result = "";
		try {
			OutputStreamWriter out = null;
			BufferedReader in = null;
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();

			// 设置连接参数
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(20000);

			// 提交数据
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			out.write(body);
			out.flush();

			// 读取返回数据
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line = "";
			boolean firstLine = true; // 读第一行不加换行符
			while ((line = in.readLine()) != null) {
				if (firstLine) {
					firstLine = false;
				} else {
					result += System.lineSeparator();
				}
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


	/**
	 * http方式POST
	 * @param url
	 * @param json
	 * @return
	 * @throws IOException
	 */
	public static HttpResult httpJsonPost2(String url, String json) throws IOException{
		HttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("param", "json"); //采用json 和general   json格式传递参数或者常规的post
		httpPost.setHeader("requestUUID", String.valueOf(System.currentTimeMillis()/1000)); //采用json 传递参数 限定一秒内只能一次请求
		httpPost.setHeader("terminal","Android"); //请求数据来源
		httpPost.setHeader("identityKey","-"); //标识身份唯一码 ＩＭＥＩ或 唯一标识符 默认值为 "-"
		if (null != json) {
			StringEntity entity = new StringEntity(json, CONTENT_ENCODING_UTF8);
			entity.setContentEncoding(CONTENT_ENCODING_UTF8);
			entity.setContentType(CONTENT_TYPE_JSON);
			httpPost.setEntity(entity);
		}
		HttpResponse result = httpClient.execute(httpPost);
		HttpEntity entity = result.getEntity();
		httpPost.releaseConnection();
		return new HttpResult(result.getStatusLine().getStatusCode(), EntityUtils.toString(entity, CONTENT_ENCODING_UTF8));
	}



}
